package com.example.demo.service;

import com.example.demo.domain.TreeEntity;
import com.example.demo.domain.TreeType;
import com.example.demo.repository.TreeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description : TODO()
 * User: h819
 * Date: 2016/1/18
 * Time: 15:38
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional(readOnly = true)
@Slf4j
public class InitializeService {


    @Autowired
    TreeRepository treeNodeRepository;

    /**
     * 初始化 TreeType 中定义的所有类型的根节点，所有节点均为该节点的子节点
     *
     * @PostConstruct // 在 Bean 初始化之前执行的操作
     * @PreDestroy //在 bean 销毁之前执行的操作
     */
    @PostConstruct // 在 InitializeService Bean 初始化之后执行的方法
    @Transactional(readOnly = false)
    public void initRootNode() {
        log.info("initialize root menu tree.");
        List<TreeEntity> rootTreeList = treeNodeRepository.findRoot();
        List<TreeType> rootTreeType = new ArrayList<>(rootTreeList.size());
        for (TreeEntity tree : rootTreeList) {
            rootTreeType.add(tree.getType());
        }

        List<TreeType> listType = Arrays.asList(TreeType.values());

        for (TreeType type : listType) {
            if (!rootTreeType.contains(type)) {
                log.info("init {} tree root node", type);
                TreeEntity root = new TreeEntity(type, "root_" + type, 0, true, null);
                treeNodeRepository.save(root);
            }
        }
    }
}
